<?php

namespace Roles\Controller;

use Zend\Mvc\Controller\AbstractActionController,
    Zend\View\Model\ViewModel;
use Roles\Model\Perfil;
use Roles\Form\PerfilForm;

class PerfilController extends AbstractActionController {

   protected $perfilTable;
   protected $permisoTable;
   protected $usuarioTable;

   private function checkLogin() {
      if (! $this->getServiceLocator()
                 ->get('AuthService')->hasIdentity()){
         return $this->redirect()->toRoute('login');
      }
   }
   private function checkRole() {
      $username = $this->getServiceLocator()->get('AuthService')->getIdentity();
      $usuario = $this->getUsuarioTable()->getUsuarioByUserName($username);

      $path = $this->getRequest()->getUri()->getPath();
      if ($path[0] != '/') $path = '/' . $path;
      $pieces = explode("/",$path);
      $module = $pieces[1]; $action = $pieces[2];
      if ($action == "") $action = "index";

      if (! $this->getServiceLocator()
                 ->get('RoleService')->hasPermission($usuario->id,$module,$action)) {

         return $this->redirect()->toRoute('restringido');
      }
   }

   public function indexAction() {

      $this->checkLogin();
      $this->checkRole();

      return new ViewModel(array(
         'perfiles' => $this->getPerfilTable()->fetchAll(),
      ));
   }

   public function agregarAction() {

      $this->checkLogin();
      $this->checkRole();

      $form = new PerfilForm();
      $form->get('submit')->setValue('Agregar');

      $request = $this->getRequest();
      if ($request->isPost()) {
         $perfil = new Perfil();
         $form->setInputFilter($perfil->getInputFilter());
         $form->setData($request->getPost());

         if ($form->isValid()) {
            $perfil->exchangeArray($form->getData());
            $this->getPerfilTable()->savePerfil($perfil);

            //Redirect to perfiles
            return $this->redirect()->toRoute('perfiles');
         }
      }
      return array('form' => $form);
   }

   public function editarAction() {

      $this->checkLogin();
      $this->checkRole();

      $id = (int) $this->params()->fromRoute('id', 0);
      if (!$id) {
         return $this->redirect()->toRoute('perfiles', array(
            'action' => 'agregar'
         ));
      }

      // Get the Perfil with the specified id. An exception is thrown
      // if cannot be found, in which case go to the  index page.
      try {
         $perfil = $this->getPerfilTable()->getPerfil($id);
      } catch(\Exception $ex) {
         return $this->reditect()->toRoute('perfiles', array(
            'action' => 'index'
         ));
      }

      $form = new PerfilForm();
      $form->bind($perfil);
      $form->get('submit')->setAttribute('value', 'Editar');

      $request = $this->getRequest();
      if ($request->isPost()) {
         $form->setInputFilter($perfil->getInputFilter());
         $form->setData($request->getPost());

         if ($form->isValid()) {
            $this->getPerfilTable()->savePerfil($form->getData());

            //Redirect to perfiles
            return $this->redirect()->toRoute('perfiles');
         }
      }

      return array(
         'id' => $id,
         'form' => $form,
      );
   }

   public function eliminarAction() {

      $this->checkLogin();
      $this->checkRole();

      $id = (int) $this->params()->fromRoute('id', 0);
      if (!$id) {
         return $this->redirect()->toRoute('perfiles');
      }

      $request = $this->getRequest();
      if ($request->isPost()) {
         $del = $request->getPost('del', 'No');
         if ($del == 'Si') {
            $id = (int) $request->getPost('id');

            //primero borrar todos los permisos asociados al perfil en la tabla perfil_permiso
            $permisos = $this->getPermisoTable()->getPermisosByPerfil($id);
            foreach($permisos as $permiso) {
               if (!is_null($permiso->id_perfil_permiso))
                  $this->getPerfilXPermisoTable()->deletePerfilXPermiso($permiso->id_perfil_permiso);
            }

            $this->getPerfilTable()->deletePerfil($id);
         }

         //Redirect to perfiles
         return $this->redirect()->toRoute('perfiles');
      }

      return array(
         'id' => $id,
         'perfil' => $this->getPerfilTable()->getPerfil($id)
      );
   }

   public function setPerfilTable(PerfilTable $perfilTable) {
      $this->perfilTable = $perfilTable;
      return $this;
   }

   public function getPerfilTable() {
      if (!$this->perfilTable) {
         $sm = $this->getServiceLocator();
         $this->perfilTable = $sm->get('Roles\Model\PerfilTable');
      }
      return $this->perfilTable;
   }

   public function getPermisoTable() {
      if (!$this->permisoTable) {
         $sm = $this->getServiceLocator();
         $this->permisoTable = $sm->get('Roles\Model\PermisoTable');
      }
      return $this->permisoTable;
   }

   public function getPerfilXPermisoTable() {
      if (!$this->perfilXpermisoTable) {
         $sm = $this->getServiceLocator();
         $this->perfilXpermisoTable = $sm->get('Roles\Model\PerfilXPermisoTable');
      }
      return $this->perfilXpermisoTable;
   }

   public function getUsuarioTable() {
      if (!$this->usuarioTable) {
         $sm = $this->getServiceLocator();
         $this->usuarioTable = $sm->get('Usuarios\Model\UsuarioTable');
      }
      return $this->usuarioTable;
   }

}
